/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The class that converts the input stream to byte array.
 *
 * @author Deep Shah
 */
public class InputStreamToByteArrayConverter {

    /**
     * The logger reference.
     */
    private static final Logger logger = Logger.getLogger(InputStreamToByteArrayConverter.class.toString());

    /**
     * The input stream reference that is to be read and converted into byte array.
     */
    private InputStream inputStream;

    /**
     * The constructor that takes in the input stream as argument.
     *
     * @param inputStream the that is to be read and converted into byte array.
     */
    public InputStreamToByteArrayConverter(final InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * The method that will read the input stream and convert it into byte array.
     *
     * @return the byte array representation of the input stream.
     */
    public byte[] convert() {
        try {
            byte[] bytes = new byte[inputStream.available()];
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead = inputStream.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
            // Close the input stream and return bytes
            inputStream.close();
            return bytes;
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        }
    }
}
